
"""
@created 2025-09-27
@Author sgzeng
@Des views home
"""
from typing import Optional

from fastapi import Request, Form, Cookie

from models.base import User


async def home(request: Request,session_id: Optional[str] = Cookie(None)):
    cookie = session_id
    session = request.session.get(cookie)
    page_data = {
        "cookie": cookie,
        "session": session
    }
    request.session.setdefault("5555","tyubuyyd")
    return request.app.state.views.TemplateResponse("item.html",{ "request":request,**page_data })

async def reg_page(request: Request):
    """
    显示注册页面
    :param request:
    :return:
    """
    user_list = await User.all()
    # 打印查询结果
    print("所有用户:",user_list)
    return request.app.state.views.TemplateResponse("reg_page.html",{"request":request })

async def reg_result(request: Request,username: str = Form(...),password: str = Form(...)):
    """
    处理注册表单提交，创建用户
    :param request:
    :param username:
    :param password:
    :return:
    """
    # 尝试创建用户
    try:
        add_user = await User.create(username=username, password=password)
        print("插入的用户ID:",add_user.pk)
        print("插入的用户名:",add_user.username)
        user_list = await User().all().values()
        # 打印查询结果
        for user in user_list:
            print(f"用户:{ user.get('username') }",user)
        get_user = await User().get_or_none(username=username)
        if not get_user:
            print("没有查询到用户数据")
            return {"info":"没有查询到用户数据" }
    except Exception as e:
        print(f"创建用户失败: {e}")
        return request.app.state.views.TemplateResponse("reg_result.html",{"request":request,"username":username,"password":password,"success":False,"error":str(e) })
    return request.app.state.views.TemplateResponse("reg_result.html",{"request":request,"username":get_user.username,"password":get_user.password,"success":True,"error":None })